package com.atguigu.tingshu.order.strategy;

import com.atguigu.tingshu.common.utils.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 订单构建策略工厂
 */
@Slf4j
@Component
public class OrderBuildStrategyFactory {

    @Autowired
    private List<OrderBuildStrategy> strategies;

    private final Map<String, OrderBuildStrategy> strategyMap = new ConcurrentHashMap<>();

    /**
     * 初始化策略映射
     */
    @PostConstruct
    public void init() {
        for (OrderBuildStrategy strategy : strategies) {
            String orderType = strategy.getOrderType();
            strategyMap.put(orderType, strategy);
            log.info("注册订单构建策略: {} -> {}", orderType, strategy.getClass().getSimpleName());
        }
    }

    /**
     * 获取订单构建策略
     *
     * @param orderType 订单类型
     * @return 订单构建策略
     */
    public OrderBuildStrategy getStrategy(String orderType) {
        OrderBuildStrategy strategy = strategyMap.get(orderType);
        ThrowUtil.throwIf(strategy == null, "不支持的订单类型: " + orderType);
        return strategy;
    }
}
